#!/usr/bin/python
import sys
import os
import subprocess
    
def help():
    return "fs-c trace [Options]\nfs-c parse [Options]\nfs-c import [Options]\nfs-c validate [Options]\nfs-c view [Options]"

def run(cmd):
    return subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT).stdout.read()

def get_fsc_root():
    mod = sys.modules[__name__]
    return os.path.normpath(os.path.join(os.path.dirname(mod.__file__), ".."))

def from_fsc_root(*args):
    return os.path.normpath(os.path.join(get_fsc_root(), *args))

def get_hadoop_cp():
    cp = []
    dirs = [os.environ["HADOOP_ROOT"],os.path.join(os.environ["HADOOP_ROOT"], "lib")]
    for dir in dirs:
        for file in os.listdir(dir):
            if file.endswith(".jar"):
                cp.append(os.path.join(dir,file))
    cp.append(os.path.join(os.environ["HADOOP_ROOT"], "conf"))
    return cp

def get_cp():
    cp = [from_fsc_root("fs-c-0.3.12.jar")]
    lib_dir = from_fsc_root("lib")
    for file in os.listdir(lib_dir):
        if file.endswith(".jar"):
            cp.append(os.path.join(lib_dir, file))
    cp.append(from_fsc_root("conf"))
    if "HADOOP_ROOT" in os.environ:
    	cp.extend(get_hadoop_cp())
    if "FSC_EXTRA_CLASSPATH" in os.environ:
        cp.append(os.environ["FSC_EXTRA_CLASSPATH"])
    return cp

def check_python_version():
    v = sys.version_info
    if v[0] != 2 or v[1] < 4:
        raise Exception("No supported python version")

def get_java_command():
    cmd_args = ["java"]
    if "JAVA_HOME" in os.environ:
        cmd_args[0] = os.path.join(os.environ["JAVA_HOME"], "bin/java")
    if "FSC_JAVA_HOME" in os.environ:
        cmd_args[0] = os.path.join(os.environ["FSC_JAVA_HOME"], "bin/java")
    return " ".join(cmd_args)
    
def check_java_version():
    try:
        r = run("%s -version" % get_java_command())
        supported_version = ["1.5", "1.6", "1.7"]
        for v in supported_version:
            if r.find(v) >= 0:
                return True
    except :
        raise Exception("Failed to detect java version")
    raise Exception("No supported java version found")

def adapt_hazelcast_config():
    from xml.dom import minidom
    hosts_file = from_fsc_root("conf/hosts")
    hosts = open(hosts_file).read().split()
    
    hazelcast_file = from_fsc_root("conf/hazelcast.xml")
    hazelcast_config_doc = minidom.parse(hazelcast_file)
    
    hosts_tag = hazelcast_config_doc.getElementsByTagName('tcp-ip')[0]
    
    if len(hosts) == 0:
        raise Exception("No hosts found in conf/hosts")
        
    for hostname in hosts:
        tag = hazelcast_config_doc.createElement("hostname")
        text = hazelcast_config_doc.createTextNode(hostname)
        tag.appendChild(text)
        hosts_tag.appendChild(tag)
    my_hazelcast_file = from_fsc_root("conf/my-hazelcast.xml")
    hazelcast_config_doc.writexml(open(my_hazelcast_file, "w"))
    return my_hazelcast_file
    
if __name__ == "__main__":
    try:
        check_python_version()
        check_java_version()

        java_class = None
        if len(sys.argv) < 2:
            print help()
            sys.exit()
        args = sys.argv[1:]
        system_properties = []
        debugging = False
        cluster = False
        for i in xrange(len(args)):
            if args[i] == "--debug":
                debugging = True
                del args[i]
                break
        for i in xrange(len(args)):
            if args[i] == "--cluster":
                cluster = True
                
        if args[0] == "trace":
            java_class = "de.pc2.dedup.fschunk.trace.Main"
            
            for arg in args[1:]:
                if arg == "--cluster":
                    cluster = True
        elif args[0] == "parse":
            java_class = "de.pc2.dedup.fschunk.parse.Main"
        elif args[0] == "import":
        	if not "HADOOP_ROOT" in os.environ:
        		print "HADOOP_ROOT not set"
        		print
        		print help()
        	java_class = "de.pc2.dedup.fschunk.handler.hadoop.Import"
        elif args[0] == "validate":
            java_class = "de.pc2.dedup.fschunk.handler.Validate"
        elif args[0] == "view":
            java_class = "de.pc2.dedup.fschunk.handler.View"
        else:
            print help()
            sys.exit()
        
        if debugging:
            system_properties.append("-Dlog4j.configuration=log4j_debug.xml")   
        
        if cluster:
            my_hazelcast_file = adapt_hazelcast_config()
            system_properties.append("-Dhazelcast.config=%s" % my_hazelcast_file)
            
        cmd_args = [get_java_command()]
        if "FSC_JXM" in os.environ:
            cmd_args.append("-Dcom.sun.management.jmxremote")
        if "FSC_XMX" in os.environ:
            cmd_args.append("-Xmx%s" % os.environ["FSC_XMX"])
        else:
            cmd_args.append("-Xmx2G")
        if "FSC_NICE" in os.environ:
            cmd_args.insert(0, "nice -%s" % os.environ["FSC_NICE"])
        cmd_args.extend(system_properties)
        cmd_args.extend(["-server", "-cp",":".join(get_cp()),java_class])
        cmd_args.extend(args[1:])
    
        cmd = " ".join(cmd_args)
        os.system(cmd)
    except KeyboardInterrupt:
        sys.exit(1)
    except SystemExit:
        sys.exit(1)
    except:
        print str(sys.exc_info())
        sys.exit(1)
    sys.exit(0)

